<?php
/*
* Copyright 2021 Baidu, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* Http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

namespace BaiduBce\Services\EipTp;

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;


/**
 * This module provides a client class for EipTp.
 */
class EipTpClient extends BceBaseClient
{

    private $signer;
    private $httpClient;
    private $prefix = '/v1';

    /**
     * The EipTpClient constructor.
     *
     * @param array $config The client configuration
     */
    function __construct(array $config)
    {
        parent::__construct($config, 'eiptp');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * Create an eiptp with the specified options.
     *
     * @param int $reservationLength
     *          The reservation length of the eiptp including 1, 6 and 12 months.
     *
     * @param string $capacity
     *          The capacity of the eiptp.
     *          When reservationLength = 1 => capacity: {"10G"/"50G"/"100G"/"500G"/"1T"/"5T"/"10T"/"50T"}
     *          When reservationLength = 6 => capacity: {"60G"/"300G"/"600G"/"3T"/"6T"/"30T"/"60T"/"300T"}
     *          When reservationLength = 12 => capacity: {"1T"/"10T"/"50T"/"100T"/"500T"/"1P"}
     *
     * @param string $deductPolicy
     *          The deduct policy of the eiptp including "FullTimeDurationPackage" and "TimeDurationPackage".
     *          The default deduct policy is "FullTimeDurationPackage", the optional parameter.
     *
     * @param string $packageType
     *          The eiptp package type.
     *          The default package type is "WebOutBytes", the optional parameter.
     *
     * @param string $clientToken
     *          if the clientToken is not specified by the user, a random String
     *          generated by default algorithm will be used.
     *
     * @param array $options
     *          The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipBpClient instance.
     *
     * @return mixed
     */

    public function createEipTp($reservationLength, $capacity,
                                $deductPolicy = null, $packageType = null, $clientToken = null, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $body = array();
        if (empty($reservationLength)) {
            throw new \InvalidArgumentException(
                'request $reservationLength should not be empty.'
            );
        }
        if (empty($capacity)) {
            throw new \InvalidArgumentException(
                'request $capacity should not be empty.'
            );
        }
        $body['reservationLength'] = $reservationLength;
        $body['capacity'] = $capacity;
        if (!empty($deductPolicy)) {
            $body['deductPolicy'] = $deductPolicy;
        }
        if (!empty($packageType)) {
            $body['packageType'] = $packageType;
        }
        $params = array();
        if (empty($clientToken)) {
            $params['clientToken'] = $this->generateClientToken();
        } else {
            $params['clientToken'] = $clientToken;
        }
        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => json_encode($body),
            ),
            '/eiptp'
        );
    }

    /**
     * Get detail of the eiptp by the passed id.
     *
     * @param string $id
     *          the eiptp id for query.
     *
     * @return mixed
     */
    public function getEipTp($id, $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        if (empty($id)) {
            throw new \InvalidArgumentException(
                '$id should not be empty.'
            );
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config
            ),
            '/eiptp/' . $id
        );
    }

    /**
     * Get a list of eiptp owned by the authenticated user filtered by specific conditions.
     *
     * @param string $id
     *          eiptp's id condition, the optional parameter.
     *
     * @param string $deductPolicy
     *          eiptp's deduct policy condition, "FullTimeDurationPackage" or "TimeDurationPackage", the optional parameter.
     *
     * @param string $status
     *          eiptp's status condition, "RUNNING", "EXPIRED" or "USED_UP", the optional parameter.
     *
     * @param string $marker
     *          The optional parameter marker specified in the original request to specify
     *          where in the results to begin listing.
     *
     * @param int $maxKeys
     *          The optional parameter to specifies the max number of list result to return.
     *          The default value is 1000.
     *
     * @param array $options
     *           The optional bce configuration, which will overwrite the
     *          default configuration that was passed while creating EipBpClient instance.
     *
     * @return mixed
     */
    public function listEipTps($id = null, $deductPolicy = null, $status = null, $marker = null, $maxKeys = 1000,
                               $options = array())
    {
        list($config) = $this->parseOptions($options, 'config');
        $params = array();
        if ($id !== null) {
            $params['id'] = $id;
        }
        if ($deductPolicy !== null) {
            $params['deductPolicy'] = $deductPolicy;
        }
        if ($status !== null) {
            $params['status'] = $status;
        }
        if ($marker !== null) {
            $params['marker'] = $marker;
        }
        if ($maxKeys !== null) {
            $params['maxKeys'] = $maxKeys;
        }
        return $this->sendRequest(
            HttpMethod::GET,
            array(
                'config' => $config,
                'params' => $params,
            ),
            '/eiptp'
        );
    }

    /**
     * Create HttpClient and send request
     *
     * @param string $httpMethod
     *          The Http request method
     *
     * @param array $varArgs
     *          The extra arguments
     *
     * @param string $requestPath
     *          The Http request uri
     *
     * @return mixed The Http response and headers.
     */
    private function sendRequest($httpMethod, array $varArgs, $requestPath = '/')
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $path = $this->prefix . $requestPath;
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);

        return $result;
    }

    /**
     * The default method to generate the random String for clientToken if the optional parameter clientToken
     * is not specified by the user.
     *
     * The default algorithm is Mersenne Twister to generate a random UUID,
     * @return String An random String generated by Mersenne Twister.
     */
    public static function generateClientToken()
    {
        $uuid = md5(uniqid(mt_rand(), true));
        return $uuid;
    }
}